package com.ruoyi.common.utils.dd;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.ruoyi.common.config.DDConstant;
import com.ruoyi.common.config.DDUrlConstant;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.http.HttpUtils;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


/**
 *  钉钉工作通知工具类
 */
@Slf4j
public class MessageUtil {
    public static String send(String userIds,OapiMessageCorpconversationAsyncsendV2Request.Msg msg) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setAgentId(DDConstant.AGENT_ID);
        request.setUseridList(userIds);
        request.setToAllUser(false);
        request.setMsg(msg);
        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, AccessTokenUtil.getAccessToken());
        System.out.println("钉钉工作通知工具类: " + rsp.getBody());
        return rsp.getBody();
    }


    /**
     * 发送群消息
     * @param markdown
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    /**
     * 发送群消息
     *
     * @param markdown Markdown消息内容
     * @param secret   签名的密钥
     * @param token    机器人访问令牌
     */
    public static void sendGroup(OapiRobotSendRequest.Markdown markdown, String secret, String token) {
        try {
            Long timestamp = System.currentTimeMillis();
            System.out.println(timestamp);
            String stringToSign = timestamp + "\n" + secret;

            // 签名生成
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            System.out.println(sign);

            // 拼接URL
            DingTalkClient client = new DefaultDingTalkClient(
                    "https://oapi.dingtalk.com/robot/send?sign=" + sign + "&timestamp=" + timestamp
            );
            OapiRobotSendRequest req = new OapiRobotSendRequest();

            req.setMsgtype("markdown");
            req.setMarkdown(markdown);

            // 发送请求
            OapiRobotSendResponse rsp = client.execute(req, token);
            System.out.println(rsp.getBody());
        } catch (NoSuchAlgorithmException e) {
            System.err.println("算法不存在：HmacSHA256，检查代码实现。");
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            System.err.println("不支持的字符编码：UTF-8，请确保环境支持 UTF-8。");
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            System.err.println("签名密钥无效，请检查密钥格式是否正确。");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("请求发送失败或响应处理失败，请检查网络连接及 API 配置。");
            e.printStackTrace();
        } catch (Exception e) {
            // 捕获其他未预料的异常
            System.err.println("发生未知错误，请检查代码逻辑和输入参数。");
            e.printStackTrace();
        }
    }

}
